//
//  UIImage+Kylin_Image.m
//  03-BuDeJie-2 TabBar设置
//
//  Created by Kylin on 16/2/10.
//  Copyright © 2016年 kylin. All rights reserved.
//

#import "UIImage+Kylin_Image.h"
#import <Photos/Photos.h>
#import <SVProgressHUD.h>

@implementation UIImage (Kylin_Image)
- (instancetype)circleImage{
    // 开启图形上下文
    UIGraphicsBeginImageContext(self.size);
    
    // 获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 设置矩形框的大小
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    
    // 添加一个圆
    CGContextAddEllipseInRect(ctx, rect);
    
    // 裁剪刚才添加的圆
    CGContextClip(ctx);
    
    // 往上面画一张画
    [self drawInRect:rect];
    
    // 从当前上下文获取一张图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 关团上下文
    UIGraphicsEndImageContext();
    
    return image;
    
    
}

+ (instancetype)circleImageWithName:(NSString *)name{
    
    // 先调用类方法然后再调用对象方法
    return [[self imageNamed:name]circleImage];
}

- (void)kylin_saveToCustomAlbumWithCompletionHandler:(void (^)(BOOL success, NSError * error))handler{
    
    // 保存到自定义机册
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        switch (status) {
                
                // 系统级别的限制,用户无法修改这个授权状态
            case PHAuthorizationStatusRestricted:{
            handler(NO, [NSError errorWithDomain:@"系统级别的限制" code:0 userInfo:nil]);
                break;
            }// 用户已经拒绝当前App访问相片数据（说明用户当初选择了“Don't Allow”）
            case PHAuthorizationStatusDenied:{
                // 如果用户不是还有做出选择,
                if (oldStatus != PHAuthorizationStatusNotDetermined) {
                handler(NO, [NSError errorWithDomain:@"用户拒绝了" code:1 userInfo:nil]);
                }
                break;
            }
            case PHAuthorizationStatusAuthorized:{
                // 获得自定义相册
                PHAssetCollection *collection = self.createdCollection;
                
                [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
                    
                    // 保存到机机胶卷
                    
                    // 获取当前保存的图片对象
        
                    PHObjectPlaceholder *createAsset = [PHAssetChangeRequest creationRequestForAssetFromImage:self].placeholderForCreatedAsset;
                                        // 将创建的相册传入,创建一个相册请求对象
                    PHAssetCollectionChangeRequest *collectionChangeRequst = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
                    
                    // 将保存到 相机胶卷 中的图片添加到 自定义相册中
                    [collectionChangeRequst insertAssets:@[createAsset] atIndexes:[NSIndexSet indexSetWithIndex:0]];
                } completionHandler:handler];
                    
        
                break;
            }
            default:
                break;
        }
    }];
}
 

- (PHAssetCollection *)createdCollection{
    // 抓取所有 [自定义相册]
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    // 从info.plist获取APP名称
    NSString *title = [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey];
    
    for (PHAssetCollection *collection in collections) {
        if ([collection.localizedTitle isEqualToString:title]) {
            
            // 自定义相册已经创建过了
            return collection;
        }
    }
    
    __block NSString *collectionID = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        
        // 创建自定义相册
        collectionID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
    } error:nil];
    
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionID] options:nil].firstObject;
}                
                
@end
